package com.gamehouse.eggpoacher;

import java.util.ArrayList;
import java.util.List;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import Models.Player;

public class WebServiceClient {

	private static final String NAMESPACE = "http://EggPoacher/";
	private static String URL = "http://eggpoacher.s20.eatj.com/EggPoacherWeb/EggPoacher?wsdl";
	private static final String SOAP_ACTION =  "http://EggPoacher";
	
	
	public WebServiceClient(){}

	public static String insertScore(Player toInsert){
		
		String methodName = "insertScore";
		String toReturn = "";
		
		SoapObject request = new SoapObject(NAMESPACE, methodName); 

		  
		  PropertyInfo propInfo=new PropertyInfo();
		  propInfo.name="player";
		  propInfo.type=PropertyInfo.STRING_CLASS;
		  request.addProperty(propInfo, toInsert.getNome());
		  PropertyInfo propInfo2 = new PropertyInfo();
		  propInfo2.name="score";
		  propInfo2.type=PropertyInfo.STRING_CLASS;
		  request.addProperty(propInfo2, toInsert.getScore());
		    
		  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 

		  envelope.setOutputSoapObject(request);
		  HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

		  try {
		    androidHttpTransport.call(SOAP_ACTION, envelope);
		  
		    SoapPrimitive  resultsRequestSOAP = (SoapPrimitive) envelope.getResponse();
		    toReturn = resultsRequestSOAP.toString();
		    
		    return toReturn;
		   
		 } 
		 catch (Exception e) {
			  
			  toReturn = "Falha ao Submeter a pontuação!";
			  return toReturn;
		 }
	}
	
	public static ArrayList<Player> getListScores(){
		
		String methodName = "getListScores";
		ArrayList<Player> listToReturn = new ArrayList<Player>();
		
		SoapObject request = new SoapObject(NAMESPACE, methodName);
		
		SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); 
		envelope.dotNet = false;

		envelope.setOutputSoapObject(request);
		HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
		
		try{
			androidHttpTransport.call(SOAP_ACTION, envelope);
			SoapObject result = (SoapObject)envelope.bodyIn;
			System.out.print(result.toString());
			int propertyCount = result.getPropertyCount();
			
			if(propertyCount>0){
                SoapObject element;
                String playerName;
                String playerScore;
                for(int i = 0;i<propertyCount;i++){
                    element = (SoapObject)result.getProperty(i);
                    element.toString();
                }
             
            }
		}catch (Exception e){System.err.print(e.getMessage());}
		return listToReturn;
	}
}
